package com.leyou.auth.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.auth.config.OSSProperties;
import com.leyou.auth.dto.AliOssSignatureDTO;
import com.leyou.auth.service.AliAuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class AliAuthServiceImpl implements AliAuthService {

    private OSSProperties prop;
    private OSS client;

    public AliAuthServiceImpl(OSSProperties prop, OSS client) {
        this.prop = prop;
        this.client = client;
    }

    @Override
    public AliOssSignatureDTO getSignature() {

        try {
//        计算过期时间
            long expireTime = prop.getExpireTime();
            long expirEndTime = System.currentTimeMillis() + expireTime;
            Date expiration = new Date(expirEndTime);
//        设置上传策略
            PolicyConditions policyConditions = new PolicyConditions();
//        文件大小限制
            policyConditions.addConditionItem(PolicyConditions.COND_CACHE_CONTROL, 0, prop.getMaxFileSize());
//        上传目录
            policyConditions.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());
//        生成策略
            String postPolicy = client.generatePostPolicy(expiration, policyConditions);
//        编码格式
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
//        生成签名
            String postSignature = client.calculatePostSignature(postPolicy);
//        封装要返回的结果

            return AliOssSignatureDTO.of(prop.getAccessKeyId(), prop.getHost(), encodedPolicy,
                    postSignature, expirEndTime, prop.getDir());
        }catch (Exception e){
            log.error("文件上传失败，原因是：{}", e.getMessage(), e);
            throw new RuntimeException("文件上传失败", e);
        }
    }


}
